package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.LoginDto;
import com.heima.model.user.pojo.User;
import com.heima.user.mapper.UserMapper;
import com.heima.user.service.UserService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author Administrator
 * @description 针对表【ap_user(APP用户信息表)】的数据库操作Service实现
 * @createDate 2022-08-26 12:19:31
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public ResponseResult login(LoginDto dto) {

        // 判断用户登录方式（游客或者用户）
        // 游客方式不存在账号、正常登录包含账号

        Map<String, Object> map = null;

        if (StringUtils.isNotBlank(dto.getPhone())) {
            // 账号不为空，用户
            // 判断账号是否存在
            String phone = dto.getPhone();
            LambdaQueryWrapper<User> userWrapper = Wrappers.lambdaQuery(User.class);
            userWrapper.eq(User::getPhone, dto.getPhone());
            User user = userMapper.selectOne(userWrapper);
            if (Objects.isNull(user)) {
                // 注册
            }
            // 密码md5处理
            String password = dto.getPassword();
            String salt = user.getSalt();
            String md5 = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            // 密码校验

            if (user.getPassword().equals(md5)) {
                // 登录成功，获取令牌
                String token = AppJwtUtil.getToken(user.getId().longValue());
                user.setPassword(null);
                user.setSalt(null);
                map = new HashMap<>(2);
                map.put("token", token);
                map.put("user", user);
            } else {
                // 登录不成功
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"密码错误");
            }
        } else {
            // 账号为空，游客
            // 获取游客令牌
            String token = AppJwtUtil.getToken(0L);
            map = new HashMap<>(1);
            map.put("token", token);
        }
        // 封装数据
        return ResponseResult.okResult(map);
    }
}




